import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
//import ma.ac.umi.jobintech.Etudiant; // Importing the class from the previous image

public class Main {

    public static void main(String[] args) {

        // 1. Setup Hibernate SessionFactory
        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                //.addAnnotatedClass(Etudiant.class) // <mapping class=""/>
                .buildSessionFactory();

        Session session = null;
        Transaction transaction = null;

        try {
            session = factory.openSession();
            transaction = session.beginTransaction();

            // --- CREATE (Save) ---
            Etudiant etu1 = new Etudiant("name", "prename", 44);
            session.save(etu1);

            // --- READ & UPDATE ---
            // Fetch the object we just saved to ensure we have the generated ID
            Etudiant etu2 = session.get(Etudiant.class, etu1.getCin());
            etu2.setNom("Updated");
            session.update(etu2);

            // --- DELETE ---
            // Note: This tries to delete an Etudiant with ID 7 specifically
            Etudiant etu3 = session.get(Etudiant.class, 7);
            if (etu3 != null) {
                session.delete(etu3);
            }

            transaction.commit();

        } catch (Exception e) {
            // annuler la transaction en cas d'erreur
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace(); // Good practice to print the error
        } finally {
            if (session != null) {
                session.close();
            }
            factory.close();
        }
    }
}